package com.aioz.security.service.impl;

import com.aioz.security.common.ResponseResult;
import com.aioz.security.entity.LoginUser;
import com.aioz.security.entity.Menu;
import com.aioz.security.mapper.MenuMapper;
import com.aioz.security.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ResponseResult getAllMenusByUserId() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = Long.valueOf(loginUser.getUser().getId().toString());
        List<Menu> menus = menuMapper.getAllMenusByUserId(userId);
        List<Menu> sonMenus = menus.stream().filter(menu -> menu.getParentId().equals(1L)).collect(Collectors.toList());
        for (Menu sonMenu : sonMenus) {
            sonMenu.setChildren(menus.stream().filter(menu -> menu.getParentId().equals(sonMenu.getId())).collect(Collectors.toList()));
        }
        return new ResponseResult(200,sonMenus);
    }
}
